package service;

import io.http.HTTPHandler;
import io.json.JsonReader;
import logic.handler.SecurityHandler;
import model.CheckBean;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * 描述：过滤器，对需要进行过滤的请求(即.action)进行过滤
 * 进行一次安全校验，因为HTTP为短连接，无法判断是APP中用户请求
 * 校验方式：当用户登陆时，传过来设备信息，将用户名与设备信息匹配，同时将表示在线状态的status由0设置为1
 * 校验方式：过滤器会判断传过来的用户名是否与设备信息匹配，status状态是否为1，是的话继续传递相应servlet
 * Created by jcala on 2016/3/16.
 */
@WebFilter(filterName = "SecurityFilter",urlPatterns = "/*.action")
public class SecurityFilter implements Filter {
    public void destroy() {
    }

    /**
     *解析发过来的请求，将请求的json数据解析为CheckBean，通过SecurityHandler进行安全校验
     * @throws ServletException
     * @throws IOException
     */
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request=(HttpServletRequest)req;
        HttpServletResponse response=(HttpServletResponse)resp;
        String jsonData= HTTPHandler.receiveFromHTTP(request);
        CheckBean bean= JsonReader.readCheck(jsonData);
        boolean check=new SecurityHandler().cheack(bean);
        if(check){
            chain.doFilter(request, response);
        }
    }
    public void init(FilterConfig config) throws ServletException {
    }

}
